package com.liruo.treasureattic.starter.httpmessagehandler.handler;

import com.liruo.treasureattic.common.httpmsg.exception.CommonResultException;
import com.liruo.treasureattic.common.httpmsg.exception.ValidatorException;
import com.liruo.treasureattic.common.httpmsg.result.BaseResponse;
import com.liruo.treasureattic.common.httpmsg.result.Errno;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception err, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
            request.setAttribute("javax.servlet.error.exception", err, 0);
        }
        log.debug("StandardRequestErr = " +
                "request.getClass=" + request.getClass() +
                "request.getLocale.getCountry=" + request.getLocale().getCountry()
                , err);

        return new ResponseEntity<>(
                BaseResponse.fail(
                        status.value(),
                        status.getReasonPhrase()
                ),
                headers,
                status
        );
    }
    @ExceptionHandler(value = ValidatorException.class)
    public BaseResponse<String> validateErr(ValidatorException err){
        log.debug("AbstractResultException, CommonResultException or ValidateException", err);
        return BaseResponse.fail(err.getCode(), err.getMessage());
    }
    @ExceptionHandler(value = CommonResultException.class)
    public BaseResponse<String> commonResultErr(CommonResultException err){
        log.debug("AbstractResultException, CommonResultException or ValidateException", err);
        return BaseResponse.fail(err.getCode(), err.getMessage());
    }
    @ExceptionHandler(value = Throwable.class)
    public BaseResponse<String> businessSystemErr(Throwable err){
        log.debug("businessSystemErr", err);
        return BaseResponse.fail(Errno.BUSINESS_SYSTEM, err.getClass().getName());
    }
}
